package com.jf3q.admin.controller;

import com.jf3q.common.constant.SysConstant;
import com.jf3q.common.vo.ResultVo;
import com.jf3q.common.exception.JfException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author:xiaojie
 * @create: 2023-05-19 16:52
 * @Description:
 */

@RestController
@RequestMapping("/oss")

@Tag(name = "oss控制层")
public class OssController {
    @Operation(summary = "上传文件到磁盘上")
    @PostMapping
    public ResultVo upload(MultipartFile file){

        if (!file.isEmpty()) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = format.format(new Date());
            File savePath=new File(SysConstant.UPLOADPATH+"/"+datePath);
            if (!savePath.exists()) {
                savePath.mkdirs();
            }

            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString().replace("-", "");
            File saveFile= new File(savePath+"/"+fileName+ suffix);
            try {
                file.transferTo(saveFile);
                return ResultVo.success("文件上传成功", "/upload/"+datePath+"/"+fileName+ suffix);
            } catch (IOException e) {
                e.printStackTrace();
                throw  new JfException(50000,"文件上传失败");
            }
        }
        throw  new JfException(50000,"文件必填");

    }

    //删除文件的
    @Operation(summary = "根据路径删除磁盘上的文件")
    @DeleteMapping
    public ResultVo del(@RequestParam String path){


        File delFile= new File(SysConstant.UPLOADPATH+path);
        if (delFile.exists()) {
            delFile.delete();
        }
        return ResultVo.success("删除成功",null);
    }
}
